package com.w.user.service.impl;

import com.w.user.entity.UserEntity;
import com.w.user.mapper.UserMapper;
import com.w.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author w²
 * @since 2020-09-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 扣减余额
     *
     * @param userId     用户id
     * @param orderPrice 订单价格
     */
    @Override
    public void reduceBalance(Integer userId, BigDecimal orderPrice) {
        // 查询用户信息
        UserEntity userEntity = userMapper.selectById(userId);
        if (userEntity == null) {
            throw new RuntimeException("用户参数非法");
        }
        // 判断用户余额
        if (userEntity.getBalance().compareTo(orderPrice) < 0) {
            throw new RuntimeException("用户余额不足");
        }
        // 修改用户信息
        userEntity.setBalance(userEntity.getBalance().subtract(orderPrice));
        userMapper.insert(userEntity);
    }
}
